using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// FMS 状态机
/// </summary>
public class FSMComponent : MonoBehaviour
{
    protected FSMType CurrentState;
    
    /// <summary>
    /// 当前状态（只读）
    /// </summary>
    public FSMType State => CurrentState;
    
    /// <summary>
    /// 之前的状态（用于Hit状态后恢复）
    /// </summary>
    public FSMType PreviousState { get; private set; }
    
    private Dictionary<FSMType, IFsmState> m_FSM = new Dictionary<FSMType, IFsmState>();

    private Entity m_Entity;

    public void Initialize()
    {
        m_FSM.TryAdd(FSMType.Idle, new IdleState());
        m_FSM.TryAdd(FSMType.Move, new MoveState());
        m_FSM.TryAdd(FSMType.Attack, new AttackState());
        m_FSM.TryAdd(FSMType.Ultimate, new UltimateState());
        m_FSM.TryAdd(FSMType.Dead, new DeadState());
        m_FSM.TryAdd(FSMType.Hit, new HitState());

        m_Entity = GetComponent<Entity>();

        ChangeStatus(FSMType.Idle);
    }

    public void ChangeStatus(FSMType targeState, params object[] args)
    {
        if (CurrentState == targeState)
        {
            return;
        }


        if (m_FSM.ContainsKey(targeState))
        {
            // 如果切换到Hit状态，保存当前状态作为PreviousState
            // 如果从Hit状态切换出去，不更新PreviousState（保持进入Hit前的状态）
            if (targeState == FSMType.Hit && CurrentState != FSMType.None && CurrentState != FSMType.Hit)
            {
                PreviousState = CurrentState;
            }
            
            if (CurrentState != FSMType.None)
            {
                m_FSM[CurrentState].Exit(m_Entity, args);
            }

            CurrentState = targeState;

            m_FSM[targeState].Enter(m_Entity, args);
        }
    }


    private void Update()
    {
        if (CurrentState == FSMType.None)
            return;

        var state = m_FSM[CurrentState];
        if (state != null)
        {
          state.Process(m_Entity);
        }
    }
}
